package com.hnkywl.sts.webservice.bg.impl;

import com.hnkywl.sts.entity.base.WebserviceLog;
import com.hnkywl.sts.service.base.WebserviceLogService;
import com.hnkywl.sts.service.htgl.BghtService;
import com.hnkywl.sts.service.jhgl.BgjhhzmxService;
import com.hnkywl.sts.webservice.bg.IContract;
import com.hnkywl.sts.webservice.bg.request.Compare;
import com.hnkywl.sts.webservice.bg.request.Contract;
import com.hnkywl.sts.webservice.bg.request.ContractDetail;
import com.hnkywl.sts.webservice.bg.request.PaymentRate;
import com.hnkywl.sts.webservice.bg.response.Response;
import com.hnkywl.sts.webservice.bg.util.ClientIPUtil;
import com.hnkywl.sts.webservice.bg.util.ConstantBg;
import com.hnkywl.sts.webservice.bg.util.StackTraceUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: nianjunyan
 * Date: 13-5-21
 * Time: 下午9:15
 * To change this template use File | Settings | File Templates.
 */
@Service
public class ContractService implements IContract, ApplicationContextAware {
    private ApplicationContext applicationContext;

    //  保供合同service
    private BghtService bghtService;
    private WebserviceLogService webserviceLogService;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        bghtService = (BghtService) applicationContext.getBean("bghtService");
        webserviceLogService = (WebserviceLogService) applicationContext.getBean("webserviceLogService");
    }

    public Response docontract(String contractXML) {
        Response res = new Response();
        String exception = "";
        Contract contract = getContracts(contractXML);
    System.out.println(contract);
        if (null == contract) {
            res.setRetCode(ConstantBg.LOSE_PARA);
            res.setRemark("缺失参数或者参数为空！");
        } else {
            // 进行数据处理，调用service里的方法
            try {
                bghtService.interfaceContract(contract);

                res.setRetCode(ConstantBg.SYN_SUCCESS);
                res.setRemark("数据同步成功！");
            } catch (Exception e) {
                e.printStackTrace();
                exception = StackTraceUtil.getStackTrace(e);
                res.setRetCode(ConstantBg.DEAL_FAIL);
                res.setRemark("数据处理错误！");
            }
        }
        webserviceLogService.saveServerLog(
                ContractService.class.getName(),
                "docontract",
                contractXML,
                "返回代码：" + res.getRetCode() + "  说明：" + res.getRemark(),
                exception,
                contract.toString()
        );
        return res;
    }

    /**
     * 解析xml转化为list
     *
     * @param contractXML
     * @return
     */
    private Contract getContracts(String contractXML) {
        Contract contract = new Contract();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            builder = factory.newDocumentBuilder();

            String encoded = "utf-8";
            if (contractXML.indexOf("gb2312") != -1) {
                encoded = "gb2312";
            }
            Document doc = builder.parse(new ByteArrayInputStream(contractXML.getBytes(encoded)));
            //合同信息
            NodeList htNodeList = doc.getElementsByTagName("contract");

            // 只能有一个主合同信息
            if (htNodeList.getLength() != 1) {
                return null;
            }
            // 合同主体信息
            String contractId = doc.getElementsByTagName("contractid").item(0).getFirstChild().getNodeValue();
            String contractNo = doc.getElementsByTagName("contractno").item(0).getFirstChild().getNodeValue();
            String providerCode = doc.getElementsByTagName("providercode").item(0).getFirstChild().getNodeValue();
            String providerName = doc.getElementsByTagName("providername").item(0).getFirstChild().getNodeValue();
            String contractPeople = doc.getElementsByTagName("contractpeople").item(0).getFirstChild().getNodeValue();
            String contractDate = doc.getElementsByTagName("contractdate").item(0).getFirstChild().getNodeValue();
            Node endDateNode = doc.getElementsByTagName("enddate").item(0);
            String endDate = "";
            if (null != endDateNode) {
                endDate = endDateNode.getFirstChild().getNodeValue();
            }
            String amount = doc.getElementsByTagName("amount").item(0).getFirstChild().getNodeValue();
            String taxRate = doc.getElementsByTagName("taxrate").item(0).getFirstChild().getNodeValue();
            String type = doc.getElementsByTagName("type").item(0).getFirstChild().getNodeValue();
            Node descNode = doc.getElementsByTagName("contractdesc").item(0);
            if (null != descNode && null != descNode.getFirstChild() && StringUtils.isNotEmpty(descNode.getFirstChild().getNodeValue())) {
                contract.setDesc(descNode.getFirstChild().getNodeValue());
            }
            String isEffect = doc.getElementsByTagName("iseffect").item(0).getFirstChild().getNodeValue();
            String departmentId = doc.getElementsByTagName("departmentid").item(0).getFirstChild().getNodeValue();
            contract.setContractId(Long.valueOf(contractId));
            contract.setContractNo(contractNo);
            contract.setProviderCode(providerCode);
            contract.setProviderName(providerName);
            contract.setContractPeople(contractPeople);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date toDate = dateFormat.parse(contractDate);
            if(StringUtils.isNotEmpty(endDate)){
                Date enddate = dateFormat.parse(endDate);
                contract.setEndDate(enddate);
            }
            contract.setContractDate(toDate);
            contract.setAmount(Double.valueOf(amount));
            contract.setTaxRate(Double.valueOf(taxRate));
            contract.setType(type);
            contract.setEffect(isEffect);
            contract.setDepartmentId(Long.valueOf(departmentId));

            // 合同付款比例
            if (null != isEffect && isEffect.equals("1")) {
                NodeList paymentRateNodeList = doc.getElementsByTagName("paymentrate");
                if (null == paymentRateNodeList || paymentRateNodeList.getLength() < 0) {
                    return null;
                }
                PaymentRate paymentRate;
                List<PaymentRate> paymentRateList = new ArrayList<PaymentRate>();
                for (int i = 0; i < paymentRateNodeList.getLength(); i++) {
                    paymentRate = new PaymentRate();
                    String month = doc.getElementsByTagName("month").item(i).getFirstChild().getNodeValue();
                    paymentRate.setMonth(Integer.valueOf(month));
                    String rate = doc.getElementsByTagName("rate").item(i).getFirstChild().getNodeValue();
                    paymentRate.setRate(Double.valueOf(rate));
                    paymentRateList.add(paymentRate);
                }

                if (null != paymentRateList && paymentRateList.size() > 0) {
                    contract.setPaymentRateList(paymentRateList);
                }
            }

            // 合同明细信息
            NodeList detailNodeList = doc.getElementsByTagName("contractdetail");
            ContractDetail contractDetail;
            List<ContractDetail> detailList = new ArrayList<ContractDetail>();
            for (int i = 0; i < detailNodeList.getLength(); i++) {
                contractDetail = new ContractDetail();
                String contractDetailId = doc.getElementsByTagName("contractdetailid").item(i).getFirstChild().getNodeValue();
                String code = doc.getElementsByTagName("code").item(i).getFirstChild().getNodeValue();
                String qty = doc.getElementsByTagName("qty").item(i).getFirstChild().getNodeValue();
                String price = doc.getElementsByTagName("price").item(i).getFirstChild().getNodeValue();
                String taxPrice = doc.getElementsByTagName("taxprice").item(i).getFirstChild().getNodeValue();
                Node brandNode = doc.getElementsByTagName("brand").item(i);
                if (null != brandNode && null != brandNode.getFirstChild() && StringUtils.isNotEmpty(brandNode.getFirstChild().getNodeValue())) {
                    contractDetail.setBrand(brandNode.getFirstChild().getNodeValue());
                }
                Node deliveryDateNode = doc.getElementsByTagName("deliverydate").item(i);
                if (null != deliveryDateNode && null != deliveryDateNode.getFirstChild() && StringUtils.isNotEmpty(deliveryDateNode.getFirstChild().getNodeValue())) {
                    contractDetail.setDeliveryDate(deliveryDateNode.getFirstChild().getNodeValue());
                }
                Node detaicNode = doc.getElementsByTagName("detaildesc").item(i);
                if (null != detaicNode && null != detaicNode.getFirstChild() && StringUtils.isNotEmpty(detaicNode.getFirstChild().getNodeValue())) {
                    contractDetail.setDesc(detaicNode.getFirstChild().getNodeValue());
                }
                contractDetail.setContractDetailId(Long.valueOf(contractDetailId));
                contractDetail.setCode(code);
                contractDetail.setQty(Double.valueOf(qty));
                contractDetail.setPrice(Double.valueOf(price));
                contractDetail.setTaxPrice(Double.valueOf(taxPrice));
                contractDetail.setZt("ybc");
                detailList.add(contractDetail);
            }
            if (null != detailList && detailList.size() > 0) {
                contract.setListDetail(detailList);
            }

            // 合同明细和计划明细对照
            NodeList compareNodeList = doc.getElementsByTagName("compare");
            Compare compare;
            List<Compare> compareList = new ArrayList<Compare>();
            if (null != compareNodeList && compareNodeList.getLength() > 0) {
                for (int i = 0; i < compareNodeList.getLength(); i++) {
                    compare = new Compare();
                    String htDetailId = doc.getElementsByTagName("cdetailid").item(i).getFirstChild().getNodeValue();
                    String detailId = doc.getElementsByTagName("detailid").item(i).getFirstChild().getNodeValue();
                    compare.setContractDetailId(Long.valueOf(htDetailId));
                    compare.setDetailId(Long.valueOf(detailId));
                    compareList.add(compare);
                }
                if (null != compareList && compareList.size() > 0) {
                    contract.setCompareList(compareList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return contract;
    }
}
